package com.cuitrip.business.home;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.app.MainApplication;
import com.cuitrip.app.rong.RongCloudEvent;
import com.cuitrip.business.home.favorite.FavoriteListFragment;
import com.cuitrip.business.home.my.MyPageFragment;
import com.cuitrip.business.home.recommend.RecommendCardListFragment;
import com.cuitrip.business.home.trip.TripServiceListFragment;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.order.OrderConversationListFragment;
import com.cuitrip.business.order.model.OrderItem;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.business.user.proxy.UserInfoProxy;
import com.cuitrip.model.ForceUpdate;
import com.cuitrip.push.PushService;
import com.cuitrip.service.R;
import com.cuitrip.util.track.TrackUtil;
import com.lab.app.BaseActivity;
import com.lab.app.workflow.IUIWorkFlow;
import com.lab.jumper.Jumper;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.schemeurl.SchemeUrlActivity;
import com.lab.schemeurl.SchemeUrlHandler;
import com.lab.schemeurl.constant.Scheme;
import com.lab.utils.MessageUtils;
import com.lab.widget.IndexViewPager;
import com.lab.widget.pager.TabPageIndicator;
import com.umeng.update.UmengUpdateAgent;

import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import jonathanfinerty.once.Once;

/**
 * 主页
 */
public class IndexActivity extends BaseActivity implements IUIWorkFlow {

    public static final String GO_TO_TAB = "go_to_tab";

    public static int RECOMMEND_TAB_INDEX = 0;
    public static int FAV_TAB_INDEX = 1;
    public static int ORDER_TAB_INDEX = 2;
    public static int MY_TAB_INDEX = 3;


    public static final int SERVICE_TAB_INDEX = 0;

    public static final String CHANGE_ROLE_KEY = "change_role";
    @Bind(R.id.ct_tab_bar)
    LinearLayout ctTabBar;

    private volatile boolean mExiting = false;
    private static final int EXIT_TIME = 2000;


    @Bind(R.id.ct_view_pager_indicator)
    TabPageIndicator mViewPagerIndicator;
    @Bind(R.id.ct_view_pager)
    IndexViewPager mViewPager;


    private MainViewPagerAdapter mMainViewPagerAdapter;

    private int defaultPageIndex = 0;
    private boolean hasNewMessage = false;

    public static void gotoTab(Context context, int tabIndex) {
        Jumper.launchActivity(context, new Intent(context, IndexActivity.class).putExtra(IndexActivity.GO_TO_TAB, tabIndex));
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        adjustPage();
        Intent intent = getIntent();
        IntentFilter filter = new IntentFilter(OrderItem.MESSAGE_UNREAD_COUNT_CHANGED_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,filter);
        if (intent != null) {
            defaultPageIndex = intent.getIntExtra(GO_TO_TAB, defaultPageIndex);
        }
        setContentView(R.layout.main_page);
        initView();
        initData();
        initListener();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        TrackUtil.trackScreenName("/home");
        mMainViewPagerAdapter = new MainViewPagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(mMainViewPagerAdapter);
        mViewPager.requestDisallowInterceptTouchEvent(true);
        mViewPager.setOffscreenPageLimit(3);
        mViewPagerIndicator.setViewPager(mViewPager);
        mViewPager.setScanScroll(true);
        mViewPager.setCurrentItem(defaultPageIndex,false);
    }

    @Override
    public void initListener() {

    }


    @Override
    public void initData() {
        UmengUpdateAgent.update(this);
        validateForceUpdate();
    }


    protected void validateForceUpdate() {
        if (!Once.beenDone(TimeUnit.HOURS, 1, MainApplication.DAILY_FORCE_UPDATE)) {
            ApiProxy apiProxy = new ApiProxy(new IProxyCallback() {
                @Override
                public boolean onProxyResult(ProxyResult<?> result) {
                    CtApiResponse response = (CtApiResponse) result.getData();
                    if (response.isResponseNormal()) {
                        if (response.result instanceof ForceUpdate) {
                            ForceUpdate update = ((ForceUpdate) response.result);
                            if (update.isNeedUpdate() && !TextUtils.isEmpty(update.getUrl())) {
                                showForceUpdate(update.getUrl(), update.isForceUpdate());
                            } else {
                                Once.markDone(MainApplication.DAILY_FORCE_UPDATE);
                            }
                        }
                    }
                    return false;
                }
            });
            UserBusiness.forceUpdate(apiProxy);
        }
    }

    private void showForceUpdate(final String url, boolean forceUpdate) {
        View view = LayoutInflater.from(this).inflate(R.layout.force_update, null);
        view.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(it);
            }
        });
        MessageUtils.createBuilder(this).setCancelable(!forceUpdate).setView(
                view).show();
    }

    private void adjustPage(){
        boolean isTraveller = UserInfoProxy.getInstance().isTraveller();
        if (isTraveller){
             RECOMMEND_TAB_INDEX = 0;
             FAV_TAB_INDEX = 1;
            ORDER_TAB_INDEX = 2;
            MY_TAB_INDEX = 3;
        }else{
            RECOMMEND_TAB_INDEX = 0;
            ORDER_TAB_INDEX = 1;
            MY_TAB_INDEX = 2;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        adjustPage();
        if (intent != null) {
            defaultPageIndex = intent.getIntExtra(GO_TO_TAB, defaultPageIndex);
            mViewPager.setCurrentItem(defaultPageIndex, false);
        }
        setIntent(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (MainApplication.getInstance().validateRong()) {
            RongCloudEvent.ConnectRong(true);
        }
        final Intent preIntent = getIntent();
        if (null != preIntent) {
            try {
                Bundle preBundle = preIntent.getExtras();
                // 判断当前Intent是否来源于SchemeUrlActivity下发,是则执行SchemeUrl操作
                if (preBundle != null && preBundle.containsKey(SchemeUrlActivity.SchemeUrl)) {
                    String scheme = preBundle.getString(SchemeUrlActivity.SchemeUrl);
                    if (!TextUtils.isEmpty(scheme) && scheme.equals(Scheme.CUITRIP.getSchemeName())) {
                        final CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
                        final int userType = preIntent.getIntExtra(PushService.USER_TYPE_KEY, -1);
                        boolean needChangeType = false;
                        if (userType != -1 && userInfo.getType() != userType) {
                            needChangeType = true;
                        }
                        if (needChangeType) {
                            showLoading();
                            IProxyCallback proxyCallback = new IProxyCallback() {
                                @Override
                                public boolean onProxyResult(ProxyResult<?> result) {
                                    hideLoading();
                                    CtApiResponse response = (CtApiResponse) result.getData();
                                    if (response.isResponseNormal()) {
                                        userInfo.setType(userType);
                                        LoginInstance.updateProfile(AppCoreRuntime.context, userInfo, true);
                                        Intent intent = new Intent(IndexActivity.this, IndexActivity.class);
                                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                        intent.putExtra(IndexActivity.GO_TO_TAB, IndexActivity.ORDER_TAB_INDEX);
                                        startActivity(intent);
                                        processScheme(preIntent.getData());
                                    } else {
                                        if (!TextUtils.isEmpty(response.msg)) {
                                            MessageUtils.showToast(response.msg);
                                        }
                                    }
                                    return true;
                                }
                            };
                            ApiProxy apiProxy = new ApiProxy(proxyCallback);
                            UserBusiness.changeType(apiProxy, userType);
                        } else {
                            processScheme(preIntent.getData());
                        }
                    }
                }
            } catch (Throwable e) {
                e.printStackTrace();
                setIntent(null);
                //容错
            }
        }
    }

    private void processScheme(Uri uri) {
        SchemeUrlHandler.getInstance().dispatch(this, uri);
        // 关键步骤,需要清除intent为Null,否则重回该Activity触发OnResume后,将重新执行上一次intent
        setIntent(null);
    }



    public void setCurrentTab(int index) {
        if (mViewPager != null) {
            mViewPager.setCurrentItem(index, false);
        }
    }

    public class MainViewPagerAdapter extends FragmentPagerAdapter implements TabPageIndicator.ImagePageAdapter {

        private String[] pageTitles = new String[]{};
        private int[] drawableResArray = new int[]{};


        public MainViewPagerAdapter(FragmentManager fm) {
            super(fm);
            if (UserInfoProxy.getInstance().isTraveller()) {
                pageTitles = getResources().getStringArray(R.array.traveller_main_pager);
                drawableResArray = new int[]{R.drawable.ct_recommend_tab, R.drawable.ct_fav_tab,
                        R.drawable.ct_order_traveller_tab, R.drawable.ct_my_tab};
            } else {
                pageTitles = getResources().getStringArray(R.array.finder_main_pager);
                drawableResArray = new int[]{R.drawable.ct_finder_trip_tab, R.drawable.ct_order_insiders_tab,
                        R.drawable.ct_finder_my_tab};
            }

        }

        @Override
        public CharSequence getPageTitle(int position) {
            return pageTitles[position];
        }


        @Override
        public int getCount() {
            int count = pageTitles.length;
            return count;
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    if (UserInfoProxy.getInstance().isTraveller()) {
                        return new RecommendCardListFragment();
                    } else {
                        return new TripServiceListFragment();
                    }

                case 1:
                    if (UserInfoProxy.getInstance().isTraveller()) {
                        return new FavoriteListFragment();
                    } else {
                        return new OrderConversationListFragment();
                    }

                case 2:
                    if (UserInfoProxy.getInstance().isTraveller()) {
                        return new OrderConversationListFragment();
                    } else {
                        return new MyPageFragment();
                    }

                case 3:
                    if (UserInfoProxy.getInstance().isTraveller()) {
                        return new MyPageFragment();
                    }
                    break;
            }
            return null;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            super.destroyItem(container, position, object);
        }

        @Override
        public int getIconImage(int position) {
            return drawableResArray[position];
        }

        @Override
        public boolean isShowRedPoint(int index) {
            boolean isTraveller = UserInfoProxy.getInstance().isTraveller();
            if (isTraveller){
                if (index == 2){
                    return hasNewMessage;
                }
            }else{
                if (index == 1){
                    return hasNewMessage;
                }
            }


            return false;
        }
    }


    @Override
    public void onBackPressed() {
        if (!mExiting) {
            mExiting = true;
            MessageUtils.showToast(R.string.feedbakc_exit_app);
            mViewPager.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mExiting = false;
                }
            }, EXIT_TIME);
        } else {
            finish();
        }
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (OrderItem.MESSAGE_UNREAD_COUNT_CHANGED_ACTION.equals(intent.getAction())) {
                hasNewMessage = intent.getBooleanExtra(OrderConversationListFragment.KEY_HAS_UNREAD_MESSAGE, false);
                mViewPagerIndicator.notifyDataSetChanged();
            }
        }
    };


}
